<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="disabled">
      <a-form-model ref="ruleForm" :model="form" :rules="rules" :labelCol="labelCol" :wrapperCol="wrapperCol"
                    slot="detail">

        <a-card title="基本信息" :bordered="false">
          <a-row>
            <a-col :span="24">
              <a-form-model-item label="一级经营类目" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="categoryId1">
                <a-select v-model="form.categoryId1" :disabled="shopType!=3" placeholder="请选择一级经营类目" style="width: 50%"
                          @change="getcategoryId2sChange">
                  <a-select-option v-for="(item,index) in categoryId1s" :key="index" :value="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>

              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="二级经营类目" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="categoryId2">

                <a-select v-model="form.categoryId2" :disabled="shopType!=3" placeholder="请选择二级经营类目" style="width: 50%"
                          @change="getcategoryId3sChange">
                  <a-select-option v-for="(item,index) in categoryId2s" :key="index" :value="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>

              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="三级经营类目" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="categoryId3">
                <a-select v-model="form.categoryId3" :disabled="shopType!=3" placeholder="请选择三级经营类目"
                          @change="changeCategoryId3" style="width: 50%">
                  <a-select-option v-for="(item,index) in categoryId3s" :key="index" :value="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="24" v-if="shopType!=3">
              <a-form-model-item label="平台商品分类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="categoryIds">
                <tip-cate-tree-select v-model="form.categoryIds" :multiple="true" :placeholder="'请选择平台商品分类'"
                                      style="width: 100%">
                </tip-cate-tree-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="24" v-if="shopType!=4">
              <a-form-model-item label="店铺商品分类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="shopCategoryIds">
                <tip-cate-tree-select v-model="form.shopCategoryIds" :type="'shop'" :disabled="shopType!=3"
                                      :multiple="true"
                                      :placeholder="'请选择店铺商品分类'" style="width: 100%">
                </tip-cate-tree-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="商品名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="title">
                <a-input v-model="form.title" :disabled="shopType!=3" placeholder="请输入商品名称"></a-input>
              </a-form-model-item>
            </a-col>

            <a-col :span="24">
              <a-form-model-item label="商品图片" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="itemImages">
                <j-image-upload :disabled="shopType!=3" :isMultiple="true" text="上传"
                                v-model="form.itemImages"></j-image-upload>
                <span>推荐尺寸：1200*1200像素；小于3M；支持png/jpeg/jpg</span>
              </a-form-model-item>
            </a-col>

            <a-col :span="24">
              <a-form-model-item label="商品短视频" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="shortVideoUrl">
                <a-input v-model="form.shortVideoUrl" :disabled="shopType!=3" placeholder="请输入商品短视频"></a-input>
                <j-upload v-model="form.shortVideoUrl" :number="1"></j-upload>
              </a-form-model-item>
            </a-col>

            <a-col :span="24">
              <a-form-model-item label="商品货号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
                <a-input v-model="form.code" :disabled="shopType!=3" placeholder="请输入商品货号"></a-input>
              </a-form-model-item>
            </a-col>

            <a-col :span="24">
              <a-form-model-item label="商品简介" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
                <a-input v-model="form.remark" :disabled="shopType!=3" placeholder="请输入商品简介"></a-input>
              </a-form-model-item>
            </a-col>

            <a-col :span="24">
              <a-form-model-item label="排序值(1为置顶)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
                <a-input-number :min="1" v-model="form.sequence" :disabled="shopType!=3"
                                placeholder="请输入排序值"></a-input-number>
              </a-form-model-item>
            </a-col>

            <a-col :span="24">
              <a-form-model-item label="是否参与分销" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isCommission">
                <a-radio-group :disabled="shopType!=3" v-model="form.isCommission">
                  <a-radio :value="0">否</a-radio>
                  <a-radio :value="1">是</a-radio>
                </a-radio-group>
              </a-form-model-item>
            </a-col>
            <a-col :span="24" v-if="form.isCommission==0">
              <a-form-model-item label="分销比例(%)" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input-number v-model="form.rate" :disabled="shopType!=3" placeholder="请输入分销比例(%)"
                                style="width: 100%"/>
              </a-form-model-item>
            </a-col>
            <a-col :span="24" v-else>
              <a-form-model-item label="分销比例(%)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="rate">
                <a-input-number v-model="form.rate" :min="0.01" :max="100.00" :precision="2" :disabled="shopType!=3"
                                placeholder="请输入分销比例(%)" style="width: 100%"/>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-card>
        <br/>
        <a-card title="物流信息" :bordered="false">
          <a-row>
            <!-- <a-col :span="24">
              <a-form-model-item label="配送方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="mode">
                <a-select v-model="form.mode" placeholder="请选择配送方式" style="width: 100%">
                  <a-select-option :key="0" :value="1">
                    快递
                  </a-select-option>
                  <a-select-option :key="1" :value="2">
                  自提
                </a-select-option>
                <a-select-option :key="2" :value="3">
                  快递加自提
                </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col> -->

            <a-col :span="24">
              <a-form-model-item label="快递运费" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="freightType">
                <a-radio-group v-model="form.freightType" :disabled="shopType!=3" @change="handleFreightTypeChange">
                  <a-radio :value="1">统一运费</a-radio>
                  <a-radio :value="2">运费模板</a-radio>
                </a-radio-group>
              </a-form-model-item>
            </a-col>
            <a-col :span="24" v-if="form.freightType==2">
              <a-form-model-item label="快递模板" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="templateId">
                <a-select v-model="form.templateId" v-if="shopType==3" placeholder="请选择快递模板" style="width: 33.33%">
                  <a-select-option v-for="(item,index) in templateIds" :key="index" :value="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
                <a v-else @click="openTpl()">{{ now_template.name }}</a>
                <a @click="handleAdd" v-if="shopType==3" style="margin-left:15px;">新增快递模板</a>
              </a-form-model-item>
            </a-col>

            <a-col :span="24" v-if="form.freightType==1">
              <a-form-model-item label="运费" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="freight">
                <a-input-number v-model="form.freight" :disabled="shopType!=3" :step="0.01" placeholder="请输入运费"
                                style="width: 100%"/>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="单品满额包邮" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="freightFreePrice">
                <a-input v-model="form.freightFreePrice" :disabled="shopType!=3" :step="0.01"
                         placeholder="单品满额包邮"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="单品满件包邮" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="freightFreeNum">
                <a-input v-model="form.freightFreeNum" :disabled="shopType!=3" placeholder="请输入单品满件包邮"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="商品重量(g)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="weight">
                <a-input-number v-model="form.weight" :disabled="shopType!=3" @change="changeWeight" :min="0" :step="1"
                                placeholder="请输入商品重量(g)"
                                style="width: 100%"/>
              </a-form-model-item>
            </a-col>

          </a-row>
        </a-card>
        <br/>
        <a-card title="价格库存" :bordered="false">
          <a-row>
            <a-col :span="24">
              <a-form-model-item label="原价" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="originalPrice">
                <a-input-number v-model="form.originalPrice" :disabled="shopType!=3" :step="0.01" placeholder="请输入原价"
                                style="width: 100%"/>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="售价" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="price">
                <a-input-number v-model="form.price" :disabled="shopType!=3" :step="0.01" placeholder="请输入售价"
                                style="width: 100%"/>
              </a-form-model-item>
            </a-col>
            <a-col :span="24" v-if="shopType==3">
              <a-form-model-item label="商品规格" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="skuSetList">
                <div class="sku-panel">
                  <div v-for="(item1, index1) in form.skuSetList" :key="index1" class="sku-set-item">
                    <div class="sku-set-name">
                      <div class="sku-set-name-label">规格名：</div>
                      <div>
                        <a-select style="width:160px;" show-search v-model="item1.id"
                                  :default-active-first-option="false" :show-arrow="false"
                                  :filter-option="false" :not-found-content="null" @focus="loadMainSkuData('', index1)"
                                  @search="loadMainSkuData($event,index1)" @change="setMainSku($event, index1)"
                                  placeholder="请选或输入规格">
                          <a-select-option v-for=" item2 in main_skus" :key="item2.id" :value="item2.id"
                                           :disabled="item2.disabled">
                            {{ item2.propName }}
                          </a-select-option>
                        </a-select>
                      </div>

                      <div style="flex:1;text-align:right;padding-right:5px;">
                        <a-button type="danger" shape="circle" icon="close" class="sku-sub-item-del"
                                  @click="delMainSku(index1)"/>
                      </div>
                    </div>
                    <div class="sku-set-value">
                      <div class="sku-set-name-label">规格值：</div>
                      <div class="sku-sub-items">
                        <div v-for="(item3, index2) in form.skuSetList[index1].items" :key="index2"
                             class="sku-sub-item mr-5">
                          <div class="sku-sub-item-box">
                            <a-select style="width:160px;" show-search v-model="item3.id"
                                      :default-active-first-option="false" :show-arrow="false"
                                      :filter-option="false" :not-found-content="null"
                                      @focus="loadSubSkuData('', item1.id,index1,index2)"
                                      @search="loadSubSkuData($event,item1.id, index1, index2)"
                                      @change="setSubSku($event, index1, index2)"
                                      placeholder="请选或输入规格">
                              <a-select-option v-for="item4 in sub_skus" :key="item4.id" :value="item4.id"
                                               :disabled="item4.disabled">
                                {{ item4.valueName }}
                              </a-select-option>
                            </a-select>

                            <a-icon type="close-circle" class="sku-sub-item-del" @click="delSubSku(index1, index2)"/>
                          </div>

                        </div>
                        <a-button type="text" @click="addSubSku(index1)">添加规格值</a-button>
                      </div>
                    </div>
                  </div>
                  <div class="sku-add-btn">
                    <a-button type="primary" icon="el-icon-plus" @click="addMainSku()">添加规格</a-button>
                  </div>
                </div>
              </a-form-model-item>
            </a-col>

            <a-col :span="24">
              <a-form-model-item label="规格明细" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="skuList">
                <div class="sku-panel" style="padding-top:0;width:100%;overflow-x:auto;">
                  <div class="sku-list">
                    <div class="sku-list-row">
                      <div class="sku-list-col flex-2" v-if="shopType==3">
                        <a-popover v-model="checkSkuVisible" title="批量设置" placement="bottom" trigger="click">
                          <div class="popover-panel" slot="content">
                            <div class="popover-panel-row">
                              <a-checkbox v-model="checkedSkuAll" @change="setCheckedSkuAll">全选</a-checkbox>
                            </div>
                            <div class="popover-panel-row">
                              <a-checkbox v-model="checkedSku1" class="w-150">库存</a-checkbox>
                              <a-input-number v-model="checkedValue1" size="small" class="pp-f-1"
                                              controls-position="right" :min="0" :step="1"/>
                            </div>
                            <div class="popover-panel-row">
                              <a-checkbox v-model="checkedSku2" class="w-150">原价</a-checkbox>
                              <a-input-number v-model="checkedValue2" size="small" class="pp-f-1"
                                              controls-position="right" :min="0" :precision="2"
                                              :step="1"/>
                            </div>
                            <div class="popover-panel-row">
                              <a-checkbox v-model="checkedSku3" class="w-150">售价</a-checkbox>
                              <a-input-number v-model="checkedValue3" size="small" class="pp-f-1"
                                              controls-position="right" :min="0" :precision="2"
                                              :step="1"/>
                            </div>
                            <div class="popover-panel-row">
                              <a-checkbox v-model="checkedSku4" class="w-150">成本价</a-checkbox>
                              <a-input-number v-model="checkedValue4" size="small" class="pp-f-1"
                                              controls-position="right" :min="0" :precision="2"
                                              :step="1"/>
                            </div>

                            <div class="popover-panel-row" style="display:flex;">
                              <a-checkbox v-model="checkedSku7" class="w-150">规格图片</a-checkbox>
                              <j-image-upload class="avatar-uploader" :accept="'image/png,image/jpeg'"
                                              style="width:112px;" text="规格图片"
                                              v-model="checkedValue7"></j-image-upload>
                            </div>

                            <div class="popover-panel-row" style="padding-top:10px;text-align:right;display:block;">
                              <a-button class="mr-10" size="small" @click="checkSkuVisible = false">关闭</a-button>
                              <a-button class="mr-10" size="small" @click="setAllSkuClear">重置</a-button>
                              <a-button type="primary" size="small" @click="setAllSku">确定</a-button>
                            </div>
                          </div>
                          <a-button type="text">批量设置</a-button>
                        </a-popover>
                      </div>
                    </div>
                    <div class="sku-list-row">
                      <div class="sku-list-col flex-2 row-head">规格组</div>
                      <div class="sku-list-col row-head is-not-null" style="text-align:center;">库存</div>
                      <div class="sku-list-col row-head is-not-null" style="text-align:center;">原价</div>
                      <div class="sku-list-col row-head is-not-null" style="text-align:center;">售价</div>
                      <div class="sku-list-col row-head is-not-null" style="text-align:center;">成本价</div>
                      <div class="sku-list-col row-head" style="text-align:center;">规格图片</div>

                    </div>
                    <div v-for="(item, index) in form.skuList" :key="index" class="sku-list-row">
                      <div class="sku-list-col flex-2" style="font-size:12px;">{{ item.valueNames }}</div>
                      <div class="sku-list-col">
                        <a-input-number v-model="item.stock" :disabled="shopType!=3" size="small" class="w-80"
                                        :controls="false" :min="0" :step="1"/>
                      </div>
                      <div class="sku-list-col">
                        <a-input-number v-model="item.originalPrice" :disabled="shopType!=3" size="small" class="w-80"
                                        :controls="false" :min="0"
                                        :precision="2" :step="1"/>
                      </div>
                      <div class="sku-list-col">
                        <a-input-number v-model="item.price" :disabled="shopType!=3" size="small" class="w-80"
                                        :controls="false" :min="0"
                                        :precision="2" :step="1"/>
                      </div>
                      <div class="sku-list-col">
                        <a-input-number v-model="item.costPrice" :disabled="shopType!=3" size="small" class="w-80"
                                        :controls="false" :min="0"
                                        :precision="2" :step="1"/>
                      </div>
                      <div class="sku-list-col">
                        <j-image-upload :disabled="shopType!=3" style="width:112px;" text="规格图片"
                                        v-model="item.imgUrl"></j-image-upload>
                      </div>

                    </div>
                  </div>
                </div>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-card>
        <br/>
        <a-card title="其他配置" :bordered="false">
          <a-row>
            <!-- <a-col :span="24">
              <a-form-model-item label="虚拟销量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="virtualDealNum">
                <a-input-number v-model="form.virtualDealNum" :step="1" placeholder="请输入虚拟销量" style="width: 100%" />
              </a-form-model-item>
            </a-col> -->
            <a-col :span="24" v-if="shopType==1">
              <a-form-model-item label="获取积分" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="earnIntegral">
                <a-input-number v-model="form.earnIntegral" :step="1" placeholder="请输入获取积分" style="width: 100%"/>
              </a-form-model-item>
            </a-col>
            <!-- <a-col :span="24">
              <a-form-model-item label="是否是新人商品" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isSole">
                <a-radio-group v-model="form.isSole" :disabled="shopType!=3">
                  <a-radio :value="0">否</a-radio>
                  <a-radio :value="1">是</a-radio>
                </a-radio-group>
              </a-form-model-item>
            </a-col>

            <a-col :span="24">
              <a-form-model-item label="是否新品" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isNew">
                <a-radio-group v-model="form.isNew" :disabled="shopType!=3">
                  <a-radio :value="0">否</a-radio>
                  <a-radio :value="1">是</a-radio>
                </a-radio-group>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="是否是VIP专享" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isVip">
                <a-radio-group v-model="form.isVip" :disabled="shopType!=3">
                  <a-radio :value="0">否</a-radio>
                  <a-radio :value="1">是</a-radio>
                </a-radio-group>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="是否海外商品" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isAbroad">
                <a-radio-group v-model="form.isAbroad" :disabled="shopType!=3">
                  <a-radio :value="0">否</a-radio>
                  <a-radio :value="1">是</a-radio>
                </a-radio-group>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="是否热卖" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isHot">
                <a-radio-group v-model="form.isHot" :disabled="shopType!=3">
                  <a-radio :value="0">否</a-radio>
                  <a-radio :value="1">是</a-radio>
                </a-radio-group>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="是否促销" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isSales">
                <a-radio-group v-model="form.isSales" :disabled="shopType!=3">
                  <a-radio :value="0">否</a-radio>
                  <a-radio :value="1">是</a-radio>
                </a-radio-group>
              </a-form-model-item>
            </a-col> -->

            <a-col :span="24" v-if="!form.id">
              <a-form-model-item label="上架状态" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="status">
                <a-radio-group v-model="form.status" :disabled="shopType!=3">
                  <a-radio :value="1">立即上架售卖</a-radio>
                  <a-radio :value="2">暂不售卖，放入仓库</a-radio>
                </a-radio-group>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-card>
        <br/>
        <a-card title="商品详情须知" :bordered="false">
          <a-row>
            <a-col :span="24">
              <a-form-model-item label="富文本介绍" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="richText">
                <j-editor v-model="form.richText" :disabled="shopType!=3"/>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="购买须知富文本" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="buyRichText">
                <j-editor v-model="form.buyRichText" :disabled="shopType!=3"/>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-card>
        <footer-tool-bar>
          <a-space>
            <a-button type="primary" @click="submitGoods" :loading="loading">提交</a-button>
            <a-button @click="()=>{$router.back()}">返回</a-button>
          </a-space>
        </footer-tool-bar>

      </a-form-model>

    </j-form-container>
    <gms-postage-rules-modal ref="modalForm" @ok="modalFormOk"></gms-postage-rules-modal>
  </a-spin>
</template>

<script>
import Vue from 'vue'
import {SHOP_TYPE, ORG_CODE} from "@/store/mutation-types"
import {httpAction, getAction} from '@/api/manage'
import pick from 'lodash.pick'
import {validateDuplicateValue} from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import JDate from '@/components/jeecg/JDate'
import JImageUpload from '@/components/jeecg/JImageUpload'
import JUpload from '@/components/jeecg/JUpload'
import JEditor from '@/components/jeecg/JEditor'
import TipCateTreeSelect from '@/components/gospel/TipCateTreeSelect'
import FooterToolBar from '@/components/tools/FooterToolBar'
import debounce from 'lodash/debounce'
import GmsPostageRulesModal from './GmsPostageRulesModal'

export default {
  name: 'GmsGoodForm',
  components: {
    JFormContainer,
    JDate,
    JImageUpload,
    JUpload,
    JEditor,
    FooterToolBar,
    TipCateTreeSelect,
    GmsPostageRulesModal
  },


  data() {
    this.loadMainSkuDataLoad = debounce(this.loadMainSkuDataLoad, 600)
    this.loadSubSkuDataLoad = debounce(this.loadSubSkuDataLoad, 600)
    var validateFreight = (rule, value, callback) => {
      if (this.form.freightType == 1) {
        callback()
      } else if (!this.form.templateTd) {
        callback(new Error('请选择快递模板'))
      } else {
        callback()
      }
    }
    var validateSkuSetList = (rule, value, callback) => {
      callback()
    }
    var validateSkuList = (rule, value, callback) => {
      // console.log('验证规格')
      // console.log(value)
      if (!value) {
        callback(new Error('请先添加商品规格'))
      } else if (value.length == 0) {
        callback(new Error('请先添加商品规格'))
      } else {
        callback()
      }
    }
    var validateCategoryIds = (rule, value, callback) => {
      if (!this.form.categoryIds) {
        callback(new Error('请选择平台商品分类'))
      } else if (this.form.categoryIds.length == 0) {
        callback(new Error('请选择平台商品分类'))
      } else {
        callback()
      }
    }
    return {
      //当前用户店铺类型1:平台，2：自营，3：店铺，4：供应商
      shopType: Vue.ls.get(SHOP_TYPE),
      //当前用户部门code
      orgCode: Vue.ls.get(ORG_CODE),
      disabled: false,
      loading: false,
      checkSkuVisible: false,
      checkedSkuAll: false,
      checkedSku1: false,
      checkedSku2: false,
      checkedSku3: false,
      checkedSku4: false,
      checkedSku5: false,
      checkedSku6: false,
      checkedSku7: false,
      checkedValue1: 0,
      checkedValue2: 0,
      checkedValue3: 0,
      checkedValue4: 0,
      checkedValue5: 0,
      checkedValue6: 0,
      checkedValue7: null,
      main_skus: [],
      sub_skus: [],
      // skuSetList: [],

      form: {
        id: null,
        freightType: 1,
        weight: 0,
        status: 1,
        isCommission: 0,
        isNew: 0,
        isVip: 0,
        isAbroad: 0,
        isHot: 0,
        isSales: 0,
        isSole: 0,
        skuList: [],
        skuSetList: [],
        sequence: 2,
        categoryId1: '',
        categoryId2: '',
        categoryId3: ''
      },
      categoryId1s: [],
      categoryId2s: [],
      categoryId3s: [],
      templateIds: [],
      labelCol: {
        xs: {span: 24},
        sm: {span: 5},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 16},
      },
      confirmLoading: false,
      rules: {
        rate: [
          {required: true, message: '请填写分销比例!'},
        ],
        categoryId1: [
          {required: true, message: '请选择经营类目!'},
        ],
        categoryId2: [
          {required: true, message: '请选择经营类目!'},
        ],
        categoryId3: [
          {required: true, message: '请选择经营类目!', trigger: 'change'},
        ]
        ,
        categoryIds: [
          {required: true, validator: validateCategoryIds},
        ],
        shopCategoryIds: [
          {required: true, message: '请选择店铺商品分类!'},
        ]
        ,
        title: [
          {required: true, message: '请输入标题!'},
        ]
        ,
        itemImages: [
          {required: true, message: '请选择商品图片!'},
        ],
        freight: [{required: true, validator: validateFreight}],
        originalPrice: [{required: true, message: '请输入原价', trigger: 'blur'}],
        price: [{required: true, message: '请输入售价', trigger: 'blur'}],
        skuSetList: [{required: true, validator: validateSkuSetList}],
        skuList: [{required: true, validator: validateSkuList}]
      },
      url: {
        list: "/mallBase/smsServiceCategory/oneList",
        add: "/mallBase/gmsGood/add",
        edit: "/mallBase/gmsGood/edit",
        queryById: "/mallBase/gmsGood/queryById"
      },
      now_template: {}
    }
  },
  computed: {},
  created() {
    this.getcategoryId1s()
    if (this.$route.query.disabled) {
      this.disabled = this.$route.query.disabled == "true" ? true : false
    }
    if (this.$route.query.id) {
      this.form.id = this.$route.query.id
      this.loadInfo()

    } else {
      this.getTemplateIds()
    }

  },
  methods: {
    handleAdd: function () {
      this.$refs.modalForm.add()
      this.$refs.modalForm.title = "新增"
      this.$refs.modalForm.disableSubmit = false
    },
    modalFormOk() {
      this.getTemplateIds()
    },
    openTpl() {
      this.$refs.modalForm.edit(this.now_template)
      this.$refs.modalForm.title = "详情"
      this.$refs.modalForm.disableSubmit = false
    },
    changeCategoryId3(e) {
      // if (this.shopType == 3) {
      for (let i = 0; i < this.categoryId3s.length; i++) {
        if (this.categoryId3s[i].id == e) {
          this.form.categoryIds = this.categoryId3s[i].smsServiceCategoryMaps
        }
      }
      // }

    },
    changeWeight() {
      if (!this.form.weight) {
        this.form.weight = 0
      }
    },
    loadInfo() {
      const self = this
      getAction("/mallBase/gmsGood/queryById", {
        id: self.form.id
      }).then(res => {
        self.form = res.result
        self.getcategoryId2s(self.form.categoryId1)
        self.getcategoryId3s(self.form.categoryId2)
        if (self.form.skuSetList && self.form.skuSetList.length > 0) {
          self.form['skuSetList'] = JSON.parse(self.form.skuSetList)
          for (let i = 0; i < self.form.skuSetList.length; i++) {
            let obj1 = {
              id: self.form.skuSetList[i].id,
              propName: self.form.skuSetList[i].name,
              disabled: true
            }
            self.main_skus.push(obj1)
            for (let j = 0; j < self.form.skuSetList[i].items.length; j++) {
              let obj2 = {
                id: self.form.skuSetList[i].items[j].id,
                valueName: self.form.skuSetList[i].items[j].name,
                disabled: true
              }
              self.sub_skus.push(obj2)
            }
          }

        } else {
          self.form['skuSetList'] = []
        }
        self.getSkuList(self.form.id)
        self.getTemplateIds()
      })
    },
    handleFreightTypeChange(e) {
      if (this.form.freightType == 1) {
        this.form.templateId = null
      } else {
        this.form.freight = 0
      }

    },


    getTemplateIds() {
      let self = this
      if (self.form.id) {
        let sysOrgCode = ''
        if (self.form.shopId == 'A00001A00001' && !self.form.supplierId) {
          sysOrgCode = 'A00001'
        } else if (self.form.shopId == 'A00001A00001' && self.form.supplierId) {
          sysOrgCode = self.form.supplierId
        } else {
          sysOrgCode = self.form.shopId
        }
        getAction("/mallBase/gmsPostageRules/list", {pageSize: 1000, sysOrgCode: sysOrgCode}).then(res => {
          if (res.success) {
            this.templateIds = res.result.records
            if (self.form.templateId) {
              for (let i = 0; i < this.templateIds.length; i++) {
                if (self.form.templateId == this.templateIds[i].id) {
                  self.now_template = this.templateIds[i]
                }
              }
            }
          } else {
            this.$message.error(res.message)
          }
        })
      } else {
        getAction("/mallBase/gmsPostageRules/list", {pageSize: 100}).then(res => {
          if (res.success) {
            this.templateIds = res.result.records
          } else {
            this.$message.error(res.message)
          }
        })
      }

    },
    getcategoryId1s() {
      let self = this
      getAction(this.url.list, {pid: ''}).then(res => {
        if (res.success) {
          this.categoryId1s = res.result
        } else {
          this.$message.error(res.message)
        }
      })
    },
    getcategoryId2sChange(pid) {
      this.form.categoryId2 = ''
      this.form.categoryId3 = ''
      this.getcategoryId2s(pid)
    },
    getcategoryId2s(pid) {
      console.log(pid)
      let self = this
      if (pid) {
        getAction(this.url.list, {pid: pid}).then(res => {
          if (res.success) {
            this.categoryId2s = res.result
          } else {
            this.$message.error(res.message)
          }
        })
      } else {
        this.categoryId2s = []
      }

    },
    getcategoryId3sChange(pid) {
      this.form.categoryId3 = ''
      this.getcategoryId3s(pid)
    },
    getcategoryId3s(pid) {
      let self = this
      if (pid) {
        getAction(this.url.list, {pid: pid}).then(res => {
          if (res.success) {
            this.categoryId3s = res.result
          } else {
            this.$message.error(res.message)
          }
        })
      } else {
        this.categoryId3s = []
      }
    },
    getSkuList(id) {
      let self = this
      getAction("/mallBase/gmsGood/querySkuById", {id: id}).then(res => {
        if (res.success) {
          if (res.result) {
            this.form['skuList'] = res.result
          } else {
            this.form['skuList'] = []
          }

        } else {
          this.$message.error(res.message)
        }
      })
    },
    submitGoods() {
      const that = this;
      this.$confirm(
        {
          title: "修改商品提示",
          content: "如果当前商品存在于商品活动库，则在商品活动库的状态会下架",
          onOk: function () {
            that.submitForm();
          }
        });
    },
    submitForm() {
      const that = this;
      // 触发表单验证
      console.log(1)
      this.$refs.ruleForm.validate((valid) => {
        console.log(2)
        if (valid) {
          if (this.form.isCommission == 1) {
            let rate = this.form.rate;
            if (rate == null || rate > 100 || rate < 0.01) {
              this.$notification.warn({message: "黄牌警告", duration: 3, description: "选择分销则必须填写比例"});
              return;
            }
          }
          console.log(3)
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.form.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          let formData = Object.assign({}, this.form)
          console.log("表单提交数据", formData)
          if (formData.skuSetList) {
            formData.skuSetList = JSON.stringify(formData.skuSetList)
          }
          httpAction(httpurl, formData, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$router.go(-1)
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
          })
        } else {
          this.$message.error("请完善信息！")
        }

      })
    },
    setCheckedSkuAll() {
      if (this.checkedSkuAll) {
        this.checkedSku1 = true
        this.checkedSku2 = true
        this.checkedSku3 = true
        this.checkedSku4 = true
        this.checkedSku5 = true
        this.checkedSku6 = true
        this.checkedSku7 = true
      } else {
        this.checkedSku1 = false
        this.checkedSku2 = false
        this.checkedSku3 = false
        this.checkedSku4 = false
        this.checkedSku5 = false
        this.checkedSku6 = false
        this.checkedSku7 = false
      }
    },
    setAllSkuClear() {
      this.checkedValue1 = 0
      this.checkedValue2 = 0
      this.checkedValue3 = 0
      this.checkedValue4 = 0
      this.checkedValue5 = 0
      this.checkedValue6 = 0
      this.checkedValue7 = null
    },
    setAllSku() {
      for (let i = 0; i < this.form.skuList.length; i++) {
        if (this.checkedSku1) {
          this.form.skuList[i].stock = this.checkedValue1
        }
        if (this.checkedSku2) {
          this.form.skuList[i].originalPrice = this.checkedValue2
        }
        if (this.checkedSku3) {
          this.form.skuList[i].price = this.checkedValue3
        }
        if (this.checkedSku4) {
          this.form.skuList[i].costPrice = this.checkedValue4
        }
        if (this.checkedSku5) {
          this.form.skuList[i].retailPrice = this.checkedValue5
        }
        if (this.checkedSku6) {
          this.form.skuList[i].supplyPrice = this.checkedValue6
        }
        if (this.checkedSku7) {
          this.form.skuList[i].imgUrl = this.checkedValue7
        }
      }
    },
    updateSkuData() {
      this.form.skuList = []
      this.getSkuData(this.form.skuSetList.length, this.form.skuSetList, 0, [])
    },
    getSkuData(count, array, start, indexs) {
      const new_start = start + 1
      if (start > count - 1) {
        return
      }
      if (start == 0) {
        indexs = new Array(array.length)
      }
      for (
        indexs[start] = 0;
        indexs[start] < array[start].items.length;
        indexs[start]++
      ) {
        if (start == count - 1) {
          let value_ids = ""
          let value_names = ""
          let objArr = []
          for (let i = count - 1; i >= 0; i--) {
            if (
              !array[start - i].items[indexs[start - i]].id ||
              !array[start - i].items[indexs[start - i]].name
            ) {
              this.form.skuList = []
              return
            }
            let obj = {
              value_id: array[start - i].items[indexs[start - i]].id,
              value_name: array[start - i].items[indexs[start - i]].name
            }
            objArr.push(obj)
          }
          objArr.sort(this.sortData)
          for (let i = 0; i < objArr.length; i++) {
            if (value_ids == "") {
              value_ids = objArr[i].value_id
              value_names = objArr[i].value_name
            } else {
              value_ids = value_ids + "," + objArr[i].value_id
              value_names = value_names + " " + objArr[i].value_name
            }
          }
          this.form.skuList.push({
            valueNames: value_names,
            valueIds: value_ids,
            imgUrl: null,
            stock: 0,
            originalPrice: 0,
            price: 0,
            costPrice: 0,
            retailPrice: 0,
            supplyPrice: 0,
          })
        }
        this.getSkuData(count, array, new_start, indexs)
      }
    },
    sortData(a, b) {
      return a.value_id - b.value_id
    },
    addMainSku() {
      this.form.skuSetList.push({
        name: "",
        id: "",
        items: [
          {
            name: "",
            id: ""
          },
        ],
      })
      this.updateSkuData()
    },
    delMainSku(index) {
      this.form.skuSetList.splice(index, 1)
      this.updateSkuData()
    },
    addSubSku(index) {
      this.form.skuSetList[index].items.push({
        name: "",
        id: ""
      })
      this.updateSkuData()
    },
    delSubSku(index1, index2) {
      this.form.skuSetList[index1].items.splice(index2, 1)
      this.updateSkuData()
    },
    setMainSku(e, index) {
      const self = this
      self.form.skuSetList[index].name = ""
      for (let i = 0; i < self.main_skus.length; i++) {
        if (self.main_skus[i].id == e) {
          self.form.skuSetList[index].name = self.main_skus[i].propName
        }
      }
      self.updateSkuData()
      console.log(self.form.skuSetList)
      for (let i = 0; i < self.form.skuSetList[index].items.length; i++) {
        self.form.skuSetList[index].items[i].name = ""
        self.form.skuSetList[index].items[i].id = ""
      }
    },
    setSubSku(e, index1, index2) {
      const self = this
      self.form.skuSetList[index1].items[index2].name = ""
      for (let i = 0; i < self.sub_skus.length; i++) {
        if (self.sub_skus[i].id == e) {
          self.form.skuSetList[index1].items[index2].name =
            self.sub_skus[i].valueName
        }
      }
      self.updateSkuData()
    },


    loadMainSkuData(value, index) {
      const self = this
      self.main_skus = []
      self.loadMainSkuDataLoad(value, index)
    },
    loadMainSkuDataLoad(value, index) {
      const self = this
      console.log()
      getAction("/mallBase/gmsGoodProp/listByPropName", {propName: value}).then((res) => {
        self.main_skus = res.result.records.filter(function (item) {
          let state = true
          item["disabled"] = false
          for (let i = 0; i < self.form.skuSetList.length; i++) {
            if (item.id == self.form.skuSetList[i].id && index != i) {
              // state = false
              item["disabled"] = true
            }
          }
          return state
        })
      })
    },
    loadSubSkuData(e, prop_id, index1, index2) {
      const self = this
      self.sub_skus = []
      self.loadSubSkuDataLoad(e, prop_id, index1, index2)
    },
    loadSubSkuDataLoad(e, prop_id, index1, index2) {
      const self = this

      getAction("/mallBase/gmsGoodPropValue/listByValueName", {propId: prop_id, valueName: e}).then(
        (res) => {
          self.sub_skus = res.result.records.filter(function (item) {
            let state = true
            item["disabled"] = false
            for (let i = 0; i < self.form.skuSetList[index1].items.length; i++) {
              if (
                index2 != i &&
                self.form.skuSetList[index1].items[i].id == item.id
              ) {
                // state = false
                item["disabled"] = true
              }
            }
            return state
          })
        }
      )
    },
  }
}
</script>
<style lang="less" scoped>
.sku-panel {
  width: 100%;
  padding: 15px;
  box-sizing: border-box;
  border: solid 1px #e9e9e9;

  .sku-set-item {
    padding-bottom: 15px;

    .sku-set-name {
      display: flex;
      padding: 5px;
      background-color: #f4f4f4;
    }

    .sku-set-name-label {
      width: 100px;
      text-align: right;
    }

    .sku-set-value {
      padding: 12px 5px;
      display: flex;

      .sku-sub-items {
        display: block;
        flex: 1;

        .sku-sub-item {
          // display: inline-block;
          float: left;
          padding-bottom: 5px;

          .sku-sub-item-box {
            position: relative;

            .sku-sub-item-del {
              display: none;
              font-size: 20px;
              position: absolute;
              color: red;
              cursor: pointer;
              top: -10px;
              right: -10px;
            }
          }

          .sku-sub-item-box:hover {
            .sku-sub-item-del {
              display: block;
            }
          }
        }

        .mr-5 {
          margin-right: 10px;
        }
      }
    }
  }

  .sku-list {
    .sku-list-row {
      display: flex;
      border-bottom: solid 1px #e9e9e9;
      line-height: 36px;

      .sku-list-col {
        padding: 2px;
        line-height: 36px;
        color: #777777;
        width: 112px;
      }

      .w-150 {
        width: 150px;
      }

      .w-80 {
        width: 105px;

        input {
          padding-left: 2px;
          padding-right: 2px;
        }
      }

      .flex-2 {
        flex: 1;
      }

      .row-head {
        color: #333;
        font-weight: 600;
      }
    }

    .sku-list-setting {
      display: flex;
      line-height: 36px;

      .setting-item {
        padding-right: 8px;
      }
    }
  }
}

.popover-panel {
  padding: 5px;
  box-sizing: border-box;

  .popover-panel-row {
    // display: flex;
    margin-bottom: 5px;
    line-height: 36px;

    .w-150 {
      width: 100px;
      display: inline-block;
    }

    .pp-f-1 {
      display: inline-block;
      width: 139px;
    }

    .mr-10 {
      margin-right: 0px;
    }
  }
}

.is-not-null:before {
  content: '*';
  color: #ff4949;
  margin-right: 4px;
}

.classBox {
  width: 100%;
  height: 100px;
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #666666;
  padding: 0 43px;
  box-sizing: border-box;

  .classBox-i {
    color: #ff4949;
    margin-right: 3px;
  }
}
</style>
